import {useUserStore} from "@/store/user.js";
import CryptoJS from 'crypto-js';

const userStore = useUserStore()
// 处理微信授权回调的 token
export const handleToken = async () => {
    const urlParams = new URLSearchParams(window.location.search)
    const token = urlParams.get('token')
    //const token = '52521104671566722796431677442826'
    if (token) {
        try {
            await userStore.queryUserByToken(token)

            // 清除 URL 中的 token 参数
            const newUrl = window.location.href.split('?')[0]
            window.history.replaceState({}, document.title, newUrl)

            return true
        } catch (error) {
            console.error('处理用户 token 失败:', error)
            return false
        }
    }
    return false
}

export const handleThirdOpenid = async () => {
    const urlParams = new URLSearchParams(window.location.search)
    const auth_data = urlParams.get('auth_data')
    //const token = '52521104671566722796431677442826'
    //alert(auth_data)
    if (auth_data) {
        let authData = atob(auth_data)
        authData = JSON.parse(authData)
        try {
            await userStore.updateUserInfo(authData)
            // 清除 URL 中的 token 参数
            const newUrl = window.location.href.split('?')[0]
            window.history.replaceState({}, document.title, newUrl)

            return true
        } catch (error) {
            console.error('处理用户 token 失败:', error)
            return false
        }
    }
    return false
}

export const getThirdOpenid = () => {
    const url = "http://tanzhesi.wxsm.quchaobai.com/wx/wechatopen/getThirdwxinfo"
    let time  = Date.now()/1000;
    const key = "MRuInI7iiUrJjAL4xcbiN0EOlPLW6kFF";
    let params = {
        app_id: 1544924178,
        open_back_url:  "http://www.lianhualamp.com/lotos/",
        open_time: time,
        user_id: userStore.userInfo.openid,
        open_sign: CryptoJS.MD5(key + time).toString()
    }
    const open_param = btoa(JSON.stringify(params))
    window.location.href = url+"?open_param="+open_param
}

// 检查用户信息并处理微信授权
export const checkUserAndAuth = () => {
    // 检查用户信息是否存在
    if (!userStore.userInfo || !userStore.userInfo.openid) {
        // 配置回调地址和状态参数
        const baseUrl = 'http://www.lianhualamp.com'  // 替换为实际的域名
        const callbackPath = '/prod-api/api/user/wxlogin/callback'
        const returnPath = '/lotos/'

        // 进行 URL 编码
        const redirectUri = encodeURIComponent(`${baseUrl}${callbackPath}`)
        const state = encodeURIComponent(`${baseUrl}${returnPath}`)

        // 构建微信授权 URL
        const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?` +
            `appid=wxb88f9de093f0c01f` +
            `&redirect_uri=${redirectUri}` +
            `&response_type=code` +
            `&scope=snsapi_userinfo` +
            `&state=${state}` +
            `#wechat_redirect`

        // 跳转到微信授权页面
        window.location.href = authUrl
        return false
    }
    return true
}
